// 通用请求拦截器
import axios from 'axios'
import { encrypt } from './jsencrypt'
import { setStorageItem, getStorageItem } from './localStorage'

const {
    timeout,
    baseApi,
    cryptApi,
    cacheApi,
} = process.env;


// 添加公共请求
const interceptorsReq = (config) => {
    var token = sessionStorage.getItem('token')
    config.headers.Authorization = 'Bearer' + ' ' + token
    config.params = {
        lang: sessionStorage.getItem('language') || 'zh-cn'
    }
}

// 添加公共响应拦截
const interceptorsRes = (response) => {
    if (response.status === 200 && response.data.code === 50000) {
        console.log('您的账户已在其他设备登录，如不是本人操作，请及时更改密码')
        // Vue.$store.dispatch('user/logout')
        // Vue.$router.push('/login')
    }
}


const createInstance = (baseURL, interceptorsFn) => {
    const instance = axios.create({
        baseURL,
        timeout: timeout || 30000
    });
    instance.interceptors.request.use((config) => {
        // 添加公共处理函数
        interceptorsReq(config)
        interceptorsFn.interceptorsReq(config);
        return config;
    }, (error) => {
        return Promise.reject(error);
    });

    instance.interceptors.response.use((response) => {
        // 添加公共处理函数
        interceptorsRes(response)
        interceptorsFn.interceptorsRes(response);
        return response.data;
    }, (error) => {
        return Promise.reject(error);
    });

    return instance;
};


/* 添加扩展其他处理函数 */
// 请求加密
const interceptorsReqEncry = (config) => {
    if (config.data) {
        config.data = {
            encrypt_data: encrypt(config.data)
        }
    }
}

// 混入对应的请求拦截对象
const interceptorsFn = {
    interceptorsReq: interceptorsReqEncry
}

// 添加一个接口缓存对象
const cache = {}
const interceptorsReqCache = (config) => {
    const cacheKey = config.url + JSON.stringify(config.params);
    // server
    if (cache[cacheKey]) {
        return Promise.resolve(cache[cacheKey]);
    }
    // client
    if (getStorageItem(cacheKey)) {
        return Promise.resolve(getStorageItem(cacheKey));
    }
}
const interceptorsResCache = (response) => {
    const cacheKey = response.config.url + JSON.stringify(response.config.params);
    // server
    cache[cacheKey] = response.data;
    // client
    setStorageItem(cacheKey, response.data)

}
// 接口缓存
const interceptorsCache = {
    interceptorsReq: interceptorsReqCache,
    interceptorsRes: interceptorsResCache
}

// 公共实例
export const request = createInstance(baseApi);
// 加密实例
export const requestEncry = createInstance(cryptApi, interceptorsFn);
// 缓存实例
export const requestCache = createInstance(cacheApi, interceptorsCache)
